#pip install psutil
import psutil
import sys
import os

#pidPath = "cls.pid"

#写入进程号
def writePid(pidPath):
    pid = str(os.getpid())
    f = open(pidPath, 'w')
    f.write(pid)
    f.close()

#读取进程号
def readPid(pidPath):
    try:
        with open(pidPath, 'r+') as f:
            line = f.readline()
            #print("saved pid: ",line)
            pid = int(line)
            return pid
    except FileNotFoundError:
        return -1

# 判断某个程序是否在运行
# 原理：获取保存的pid，通过pid获取程序名，再按程序名进行判断
def ifProcessRunning(pidPath):
    processName = getProcessName()
    result = False
    pidRunning = readPid(pidPath)
    if pidRunning == -1:
        return result
    try:
        if (psutil.Process(pidRunning).name() == processName):
            result = True
    except psutil.NoSuchProcess:
        result = False
    return result

#获取当前进程名
def getProcessName():
    # 获取当前进程的PID
    pid = os.getpid()
    # 根据PID获取当前进程的名字
    process = psutil.Process(pid)
    process_name = process.name()

    #print("当前进程的名字是：", process_name)
    return process_name



